package chinatelecom.feilong.framework.web.license.controller;

import chinatelecom.feilong.framework.common.controller.BaseController;
import chinatelecom.feilong.framework.web.license.dao.ILicenseMainDao;
import chinatelecom.feilong.framework.web.license.entity.License;
import chinatelecom.feilong.framework.web.license.entity.LicenseMain;
import chinatelecom.feilong.framework.web.license.entity.LicenseTemplate;
import chinatelecom.feilong.framework.web.license.service.ILicenseService;
import chinatelecom.feilong.framework.web.license.service.ILicenseTemplateService;
import chinatelecom.feilong.framework.web.manager.entity.VerifyLicenseModel;
import chinatelecom.feilong.framework.web.manager.service.ILicenseManagerService;
import com.alibaba.fastjson.JSON;
import com.ideal.license.core.model.LicenseModel;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  license
 */
@Controller
@RequestMapping("/license/")
public class LicenseController extends BaseController {
    @Resource
    private ILicenseService licenseService;
    @Resource
    private ILicenseTemplateService licenseTemplateService;
    @Resource
    private ILicenseManagerService licenseManagerService;

    @RequestMapping(value="license_build")
    public String licenseBuild(final HttpServletRequest request, License license, RedirectAttributes redirectAttributes){
        return "modules/license/license_build";
    }
    @RequestMapping(value="license_check")
    public String licenseCheck(final HttpServletRequest request,License license,RedirectAttributes redirectAttributes){
        return "modules/license/license_check";
    }

    /**
     * 新增.
     * @param license
     * @return
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> save(@ModelAttribute License license) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            licenseService.saveLicense(license);
            map.put("isSuccess", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isSuccess", false);
            map.put("msg", e.getMessage());
        }

        return map;
    }


    /**
     * 续期license
     * @param request
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value="license_renewal")
    public String  license_renewal(HttpServletRequest request,Model model,String id){

        if(StringUtils.isNotEmpty(id)){
            License license = licenseService.findByID(Integer.valueOf(id));
            model.addAttribute("license", license);
        }
        return "modules/license/license_renewal";
    }

    @RequestMapping(value = "verfy", method= RequestMethod.POST,produces="text/html;charset=utf-8")
    @ResponseBody
    public Map<String, Object> upload(String subject, String edition, HttpServletResponse response, HttpServletRequest request,
                                      @RequestParam(value="licFile", required=false)MultipartFile file)  {
        String path = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
        File dir = new File(path);
        Map<String, Object> map = new HashMap<String, Object>();

        if (dir.exists()) {
            dir.delete();
        }

        dir.mkdir();

        VerifyLicenseModel vmodel = new VerifyLicenseModel();
        vmodel.setEdition(edition);
        vmodel.setSubject(subject);

        try {
            String filePath = path + file.getOriginalFilename();
            file.transferTo(new File(filePath));
            vmodel.setPath(filePath);
            LicenseModel model = licenseManagerService.verifyLicense(vmodel);
            map.put("isSuccess", true);
            map.put("model", model);

        } catch (Exception e) {
            map.put("isSuccess", false);
            map.put("message", e.getMessage());
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 获取license的版本名称，供前台展示使用
     * @return
     */
    @RequestMapping("license_licenseTemplate")
    @ResponseBody
    public List<LicenseTemplate> obtainLicenseType() {
        List<LicenseTemplate> licenseTemplate = licenseTemplateService.getLicenseType();
        return licenseTemplate;
    }

    @RequestMapping(value="license_info")
    public String licenseCheck(final HttpServletRequest request){
        return "modules/license/user_license";
    }


    @RequestMapping(value="license_list")
    public String  roleList(HttpServletRequest request,Model model){
        return "modules/license/license_list";
    }

    /**
     * 异步获取角色数据
     //* @param request
     * @param rows
     * @param page
     * @return
     */
    @RequestMapping(value="ajax_license_data")
    @ResponseBody
    public Map ajaxLicenseData(HttpServletRequest request, Integer rows, Integer page, String sortName, String sortValue){
        Integer pageSize = rows==null?10:rows;
        Integer curPage = page==null?0:page-1;
        Pageable pageable = new PageRequest(curPage, pageSize);
        Map<String,Object> searchParams = new HashMap<String, Object>();
        String subject = request.getParameter("subject");
        if(StringUtils.isNotEmpty(subject)){
            searchParams.put("LIKE_subject",subject);
        }

        Page<LicenseMain> rolePage = licenseService.listPageByParams(searchParams,pageable,sortName,sortValue);
        Map data = new HashMap();
        data.put("total",rolePage.getTotalElements());
        data.put("rows",rolePage.getContent());
        return  data;
    }

    /**
     * 通过id查询具体的license信息.
     * @param request
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value="license_showed")
    @ResponseBody
    public Map  license_forch(HttpServletRequest request,Model model,String id){
        Map data = new HashMap();
        Integer mainId = 0;
        List<License> list = new ArrayList<License>();

        if (StringUtils.isNumeric(id)) {
            mainId = Integer.valueOf(id);
            list = licenseService.listByMainId(mainId);
        }

        data.put("rows",list);

        return data;
    }

    @RequestMapping("/license_delete")
    public String menuDelete(@RequestParam(required=true) String id, RedirectAttributes redirectAttributes ){
        licenseService.deleteCascade(Integer.valueOf(id));
        addMessage(redirectAttributes, "删除license成功");
        return "redirect:./license_list";
    }

    @RequestMapping("download")
    public String downloadJob(HttpServletResponse response, Integer id) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File file = null;
        License license = licenseService.findByID(id);
        String path = license.getPath();
        try {
            file = new File(path);
            String fileName = URLEncoder.encode(file.getName(), "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
        return null;
    }

    @RequestMapping(value="license_show")
    public String  license_show(HttpServletRequest request,Model model,String id){

        if(StringUtils.isNotEmpty(id)){
            License license = licenseService.findByID(Integer.valueOf(id));
            model.addAttribute("license", license);
        }
        return "modules/license/license_show";
    }


    @RequestMapping("/license_buidSuccessPage")
    public String returnSucceedPage( final HttpServletRequest request,RedirectAttributes redirectAttributes ){
        return "modules/license/successToLicense";
    }

    /**
     * 保存续期信息
     * @param license
     * @return
     */
    @RequestMapping(value = "renewalLicese", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> renewalLicese(@ModelAttribute License license) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            licenseService.renewalLicense(license);
            map.put("isSuccess", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isSuccess", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }
}
